package com.yzh.pinboard.FileExplore;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.yzh.pinboard.R;

import java.io.File;


public class FileExploreAdapter extends BaseAdapter {

    private Context mContext;

    private File[] mFiles;

    private LayoutInflater layoutInflater;

    FileExploreAdapter(Context context, File[] files) {
        this.mContext = context;
        this.mFiles = files;

        layoutInflater = LayoutInflater.from(context);
    }

    public void setData(File[] files) {
        mFiles = files;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return mFiles.length;
    }

    @Override
    public File getItem(int i) {
        return mFiles[i];
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(
            int i,
            View convertView,
            ViewGroup viewGroup) {

        ViewHolder holder;

        if (convertView == null) {
            convertView = layoutInflater.inflate(R.layout.item_file, null);

            holder = new ViewHolder(convertView);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }


        holder.bindData(mFiles[i]);

        return convertView;
    }


    private class ViewHolder {

        ImageView icon;
        TextView title;
        TextView info;


        ViewHolder(View v) {
            icon = (ImageView) v.findViewById(R.id.imageView_icon);
            title = (TextView) v.findViewById(R.id.textView_name);
            info = (TextView) v.findViewById(R.id.textView_info);
        }


        void bindData(File file) {
            if (file.isDirectory()) {
                icon.setImageResource(R.drawable.ic_folder);
            } else if (file.getName().endsWith("jpg")) {
                Glide.with(mContext).load(file.getPath()).into(icon);
            } else {
                icon.setImageResource(R.drawable.ic_folder);

            }

            title.setText(file.getName());

            info.setText(file.isFile()
                    ? String.format(mContext.getResources().getString(R.string
                    .byte_length), file.length())
                    : String.format(mContext.getResources().getString(R.string
                    .dir_number), file.list().length));
        }
    }

    static String getExtension(String file) {
        return file.substring(file.lastIndexOf(".") + 1);
    }

}
